package com.ruoyi.electronicFence.task;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.electronicFence.domain.ReceiveEFData;
import com.ruoyi.electronicFence.service.ITEfAlarmService;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import lombok.Getter;
import lombok.Setter;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Component
@Getter
@Setter
/*
电子围栏接收报警的定时任务
*/
public class ReceiveAlarmDataScheduler implements SchedulingConfigurer {

    @Value("${scheduler.receiveAlarmDataUpdateCron}")
    private String initialMonitorStatusUpdateCron;
    private boolean isLastReceiveCornErr;
    @Value("${scheduler.receiveAlarmDataUpdateCron}")
    private String monitorStatusUpdateCron;
    @Value("${hk.switch}")
    private String HK_SWITCH;
    @Value("${system.name}")
    private String SYSTEM_NAME;
    @Autowired
    private ITEfAlarmService iTEfAlarmService;

    @Override
    //配置定时任务
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> {
//            AlarmData();
        }, triggerContext -> {
            // 使用CronTrigger触发器，动态修改cron表达式来操作循环规则
            CronTrigger cronTrigger;
            if (isLastReceiveCornErr) {
                cronTrigger = new CronTrigger(initialMonitorStatusUpdateCron);
            } else {
                try {
                    cronTrigger = new CronTrigger(monitorStatusUpdateCron);
                    isLastReceiveCornErr = false; // 设置为false，表示当前cron表达式有效
                } catch (IllegalArgumentException e) {
                    System.out.println("上次接收的 monitorStatusUpdateCron: \"" + monitorStatusUpdateCron + "\" 格式错误，将使用初始值");
                    cronTrigger = new CronTrigger(initialMonitorStatusUpdateCron);
                    isLastReceiveCornErr = true; // 设置为true，表示当前cron表达式无效
                }
            }
            return cronTrigger.nextExecutionTime(triggerContext);
        });
    }

    //执行的定时任务内容
    public  String AlarmData(){
        String url ="";
        url="http://192.168.3.43:8080/electronicFence/receive-alarm-data";
        LocalDateTime now = LocalDateTime.now();

        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd%20HH:mm:ss");
        // 格式化时间
        String formattedDateTime = now.format(formatter);
        url=url+"?dataTime="+formattedDateTime;
        System.out.println(url);
        // 发送 GET 请求并获取响应
        HttpResponse<String> response = Unirest.get(url)
                .header("Content-Type", "application/json")
                .header("Accept", "*/*")
                .header("Host", "192.168.3.43:8080")
                .header("Connection", "keep-alive")
                .asString();

//    // 输出响应内容和状态码
//        System.out.println("Response status: " + response.getStatus());
//        System.out.println("Response body: " + response.getBody());
        String body = response.getBody(); // 将 JSON 字符串转换为 JSONObject
        JSONObject jsonObject = new JSONObject(body);

        // 将 JSONObject 转换为 Map
        Map<String, Object> map = new JSONObject(body).toMap();
        //进行数据转换入库dataConversion
        Map<String, Object> map1 = dataConversion(map);
        Object msg = map.get("Msg");
        return response.getBody();
    }

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();

//        String s = updateMonitorStatusTask2();

//        System.out.println(s);
        LocalDateTime now2 = LocalDateTime.now();
        // 计算时间差
        Duration duration = Duration.between(now, now2);
        long seconds = duration.getSeconds();

        System.out.println("Seconds difference: " + seconds);

    }

    public AjaxResult dataConversion(Map<String, Object> map ) {
        AjaxResult ajaxResult = new AjaxResult();
        //如果响应成功 则向报警数据存数
       if (map.get("Result").equals("Succeed")){
           //new 接收报警数据对象
           ReceiveEFData receiveEFData = new ReceiveEFData();
           //解析控制器类型
           String controllerStatus = (String)map.get("controllerStatus");
           receiveEFData.setControllerStatus(controllerStatus);
//           if (controllerStatus.equals("1")||controllerStatus.equals("2")){
               //解析时间
               String alarmTime = (String)map.get("alarmTime");
               DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
               LocalDateTime alarmDateTime = LocalDateTime.parse(alarmTime, formatter);
               receiveEFData.setAlarmTime(alarmDateTime);
               //解析IP
               String controllerIP = (String)map.get("controllerIP");
               receiveEFData.setControllerIP(controllerIP);


               String equipmentStatus = (String)map.get("equipmentStatus");
               receiveEFData.setEquipmentStatus(equipmentStatus);

               String pictureUrl = (String)map.get("pictureUrl");
               receiveEFData.setPictureUrl(pictureUrl);

               // 获取值
               Object value = map.get("alarmType");
               String[] alarmType = new String[0];
               if (value != null && value instanceof String[]) {
                    alarmType = (String[]) value;
               }
               receiveEFData.setAlarmType(alarmType);

               Map<String,List<Map<String,Object>>> personCardInfoMap = (Map<String,List<Map<String,Object>>>)map.get("personCardInfo");
               receiveEFData.setPersonCardInfoMap(personCardInfoMap);
               int i = iTEfAlarmService.InboundDataOftAlarm(receiveEFData);
               if (i>0){
                   ajaxResult.isSuccess();
                   ajaxResult.put("code",200);
                   ajaxResult.put("msg","入库成功");
               }
//           }

       }else {
           ajaxResult.isError();
           ajaxResult.put("code",500);
           ajaxResult.put("msg","入库失败");
       }
        return ajaxResult;
    }


}
